<template>
  <div>
    <Card>
      <tables ref="tables" editable searchable search-place="top" v-model="tableData" :columns="columns" />
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为excel文件</Button>
      <Button style="position:absolute; top: 27px; right: 17px;" type="primary" @click="addMachineGroup">新增角色</Button>
    </Card>
    <Modal v-model="deleteVisible" @on-ok="handleDelete">
      <p>是否确定删除该条记录？</p>
    </Modal>
    <Modal v-model="visible" :title="title" :mask-closable="false" @on-ok="okModal" @on-cancel="cancelModal">
      <Row class="row" style="margin-top:0;">
        <Col span="6">
        <strong class="title">角色名称：</strong>
        </Col>
        <Col span="18">
        <Input class="form" v-model="roleName" placeholder="请输入角色名称" />
        </Col>
      </Row>
      <Row class="row">
        <Col span="6">
        <strong class="title">描述：</strong>
        </Col>
        <Col span="18">
        <Input class="form" v-model="roleDescribe" placeholder="请输入描述" type="textarea" :rows="4" />
        </Col>
      </Row>
    </Modal>
    <Modal v-model="empowerVisible" title="权限设置" :mask-closable="false" @on-ok="okModalEmpower"
      @on-cancel="cancelModalEmpower">
      <Tree :data="empowerData" show-checkbox multiple></Tree>
    </Modal>
  </div>
</template>

<script>
import Mock from 'mockjs'
import Tables from '_c/tables'
import { roleNames } from '@/mock/data/option-data.js'
import rcRequest from 'rc-request'
import jsCookie from 'js-cookie'

export default {
  name: 'role_management_page',
  components: {
    Tables
  },
  data() {
    return {
      columns: [
        { title: '角色名称', key: 'roleName' },
        { title: '描述', key: 'roleDescribe' },
        { title: '创建时间', key: 'createDate' },
        {
          title: '操作',
          key: 'action',
          width: 170,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.title = '修改角色';
                    this.visible = true;
                    this.roleName = params.row.roleName;
                    this.roleDescribe = params.row.roleDescribe;
                    this.createDate = params.row.createDate;
                    this.empowerData = JSON.parse(JSON.stringify(params.row.empowerData));
                    this.machineGroupIndex = params.row.initRowIndex;
                  }
                }
              }, '修改'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.deleteIndex = params.index;
                    this.deleteVisible = true;
                  }
                },
              }, '删除'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'success',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.empowerIndex = params.row.initRowIndex;
                    this.getRoleAuthority();
                  }
                },
              }, '授权'),
            ]);
          }
        }
      ],
      tableData: [],
      // 权限列表
      authorityList: [],
      // 新增/修改角色
      title: '新增角色',
      visible: false,
      roleName: '',
      roleDescribe: '',
      createDate: '',
      machineGroupIndex: -1,
      // 授权
      empowerVisible: false,
      empowerData: [],
      empowerIndex: -1,
      // 删除
      deleteVisible: false,
      deleteIndex: 0,
    }
  },
  methods: {
    exportExcel() {
      this.$refs.tables.exportCsv({
        filename: `角色-${(new Date()).valueOf()}.csv`
      })
    },
    addMachineGroup() {
      this.title = '新增角色';
      this.visible = true;
      this.roleName = '';
      this.roleDescribe = '';
      this.machineGroupIndex = -1;
    },
    async okModal() {
      // 新增
      if (this.machineGroupIndex < 0) {
        await rcRequest({
          method: 'post',
          url: '/role/insert_role_info',
          data: {
            name: this.roleName,
            description: this.roleDescribe,
          },
        })
        this.getListData()
        this.$Message.success('新增成功')
        return;
      }

      // 修改
      await rcRequest({
        method: 'post',
        url: '/role/update_role_info',
        data: {
          name: this.roleName,
          description: this.roleDescribe,
          role_id: this.tableData[this.machineGroupIndex].id,
        },
      })
      this.tableData.splice(this.machineGroupIndex, 1, {
        ...this.tableData[this.machineGroupIndex],
        roleName: this.roleName,
        roleDescribe: this.roleDescribe,
      });
      this.$Message.success('修改成功')
    },
    cancelModal() { },
    async okModalEmpower() {
      // 授权
      const selectedItem = this.tableData[this.empowerIndex];

      // 选中的权限
      const selectedAuthority = [];
      this.empowerData.map(item => {
        if (!!item.checked) {
          selectedAuthority.push(item.id)
        }

        item.children.map(sItem => {
          if (!!sItem.checked) {
            selectedAuthority.push(sItem.id)
          }
        })
      })

      // 请求
      await rcRequest({
        method: 'post',
        url: '/authority/add_role_authority_info',
        data: {
          role_id: selectedItem.id,
          array_authority_id: selectedAuthority.join(','),
        },
      })

      // 更新数据
      selectedItem.empowerData = this.empowerData;
      this.$Message.success('权限设置成功');
    },
    cancelModalEmpower() { },
    // 删除数据
    async handleDelete() {
      await rcRequest({
        method: 'post',
        url: '/role/delete_role_info',
        data: {
          role_id: this.tableData[this.deleteIndex].id,
        },
      })
      this.tableData.splice(this.deleteIndex, 1)
      this.$Message.success('删除成功')
    },
    // 获取列表数据
    async getListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/role/select_role_list',
        data: { }
      })
      this.tableData = data.map(item => ({
        id: item.id,
        roleName: item.name,
        roleDescribe: item.description,
        createDate: item.create_time,
        empowerData: JSON.parse(JSON.stringify(this.authorityList)),
      }))
    },
    // 获取权限列表
    async getAuthorityList() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/authority/select_authority_list',
        data: { },
      })
      this.authorityList = data.map(item => ({
        id: item.id,
        title: item.name,
        expand: false,
        children: item.children.map(sItem => ({
          id: sItem.id,
          title: sItem.name,
          expand: false,
        }))
      }))
    },
    // 获取角色权限
    async getRoleAuthority() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/authority/select_role_authority_info2',
        data: {
          role_id: this.tableData[this.empowerIndex].id,
        }
      })
      this.empowerData = JSON.parse(JSON.stringify(this.tableData[this.empowerIndex].empowerData));
      this.empowerData = this.empowerData.map(item => ({
        ...item,
        checked: data.includes(item.id.toString()),
        children: item.children.map(sItem => ({
          ...sItem,
          checked: data.includes(sItem.id.toString()),
        }))
      }))
      this.empowerVisible = true;
    },
  },
  async mounted() {
    await this.getAuthorityList()
    this.getListData()
  }
}
</script>

<style scoped>
.row {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.title {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

.form {
  width: 85%;
}
</style>
